package controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.LicenseDetailDao;




/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadPicServlet")
public class UploadPicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadPicServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String filename="E:\\test.txt";
		String lic_id=null;
		FileItemFactory  factory=new DiskFileItemFactory();
		ServletFileUpload upload=new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		String path=null;
		try {
			List<FileItem> parseRequest=upload.parseRequest(request);
			for(FileItem i:parseRequest)
			{
				if(i.isFormField())
				{
					lic_id=i.getString();
					System.out.println(i.getName());
				}else {
					String name=i.getName();
					filename=name.substring(name.lastIndexOf("."),name.length());
					Date date=new Date();
					SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddhhmmss");
					String dateStr=simpleDateFormat.format(date);
					filename=dateStr+filename;
					path="E:\\upload\\"+filename;
					System.out.println(path);
					File file=new File(path);
					try {
						i.write(file);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}	
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		int id=(int) request.getSession().getAttribute("id");
		System.out.println(id);
		LicenseDetailDao ldd=new LicenseDetailDao();
		ldd.addLicense(lic_id, 1, path);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
